from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.utils import timezone
from django.db.models import Q
from .models import TodoItem
from .serializers import TodoItemSerializer

class TodoItemView(APIView):
    permission_classes = []

    def get(self, request, item_id=None):
        """获取待办事项"""
        if item_id:
            try:
                item = TodoItem.objects.get(id=item_id)
                serializer = TodoItemSerializer(item)
                return Response(serializer.data)
            except TodoItem.DoesNotExist:
                return Response(
                    {"error": "Item not found"}, 
                    status=status.HTTP_404_NOT_FOUND
                )
        
        # 获取用户的所有待办事项
        user_id = request.GET.get('user_id')
        items = TodoItem.objects.filter(user_id=user_id)
        serializer = TodoItemSerializer(items, many=True)
        return Response(serializer.data)

    def post(self, request):
        """创建待办事项"""
        data = request.data.copy()
        # 确保使用 user_id 设置 user 字段
        data['user'] = data.get('user_id')
        
        serializer = TodoItemSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def put(self, request, item_id):
        """更新待办事项"""
        try:
            item = TodoItem.objects.get(id=item_id)
            data = request.data.copy()
            if 'user_id' in data:
                data['user'] = data.pop('user_id')
            
            serializer = TodoItemSerializer(item, data=data, partial=True)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except TodoItem.DoesNotExist:
            return Response(
                {"error": "Item not found"}, 
                status=status.HTTP_404_NOT_FOUND
            )

    def delete(self, request, item_id):
        """删除待办事项"""
        try:
            item = TodoItem.objects.get(id=item_id)
            item.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except TodoItem.DoesNotExist:
            return Response(
                {"error": "Item not found"}, 
                status=status.HTTP_404_NOT_FOUND
            )

class TodoStatisticsView(APIView):
    """待办事项统计视图"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """获取待办事项统计信息"""
        # 获取所有待办事项
        items = TodoItem.objects.filter(todo_list__user=request.user)
        
        # 统计各状态的数量
        status_stats = {
            'total': items.count(),
            'pending': items.filter(status='pending').count(),
            'in_progress': items.filter(status='in_progress').count(),
            'completed': items.filter(status='completed').count(),
            'cancelled': items.filter(status='cancelled').count(),
        }
        
        # 统计各优先级的数量
        priority_stats = {
            'high': items.filter(priority=3).count(),
            'medium': items.filter(priority=2).count(),
            'low': items.filter(priority=1).count(),
        }
        
        # 统计逾期任务
        overdue_count = items.filter(
            due_date__lt=timezone.now(),
            status__in=['pending', 'in_progress']
        ).count()
        
        return Response({
            'status': status_stats,
            'priority': priority_stats,
            'overdue': overdue_count
        })
